package com.tron.dobest.java.tronnet.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 测试方法：
 * 1 cmd  telnet 127.0.0.1 6666
 * 2 CTRL + ]
 * 3 send + message
 */
public class BIOServer {
    public static void main(String[] args) throws IOException {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("===服务器启动===");
        while (true) {
            System.out.println("阻塞，等待连接...");
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");
            threadPool.execute(()->{
                System.out.println("开启线程"+Thread.currentThread().getId()+"处理消息");
                try {
                    InputStream inputStream = socket.getInputStream();
                    System.out.println("阻塞，等待写入数据...");
                    byte[] buff = new byte[1024];
                    int read = 0;
                    while ((read = inputStream.read(buff)) != -1) {
                        System.out.println(new String(buff,0,read, StandardCharsets.UTF_8));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}
